package com.delu.controller;

import com.delu.data.Result;
import com.delu.em.ResultEnum;
import com.delu.entity.Message;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("mqProducer")
public class MessageController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    //发送短信
    @GetMapping("send")
    public Result send(@RequestParam("phoneNum") String phoneNum)   {
        if (StringUtils.isEmpty(phoneNum)) {
            return Result.response(ResultEnum.ERROR);
        }
        rocketMQTemplate.convertAndSend("phoneNumMessage",phoneNum);

        return Result.response(ResultEnum.SUCCESS);
    }

    //发送短信
    @GetMapping("sends")
    public Result sends(@RequestParam("phoneNum") String phoneNum,@RequestParam("body")String body)   {
        if (StringUtils.isEmpty(phoneNum)) {
            return Result.response(ResultEnum.ERROR);
        }
        Message message = new Message();
        message.setPhone(phoneNum);
        message.setBody(body);
        String s = String.valueOf(JSONObject.fromObject(message));
        rocketMQTemplate.convertAndSend("sendMessage",s);
        return Result.response(ResultEnum.SUCCESS);
    }

    //校验短信
    @GetMapping("Check")
    public Result CheckCodeByRedis(@RequestParam("phoneNum") String phoneNum,@RequestParam("code") String code){
        //code 用户传入验证码 ,redisCode  redis保存的用户验证码
        String redisCode = (String) redisTemplate.boundValueOps(phoneNum).get();
        if (code.equals(redisCode)){
            return Result.response(ResultEnum.SUCCESS).setData(1);
        }else {
            return Result.response(ResultEnum.ERROR).setData(2);
        }
    }
}
